<?php
//error_reporting(E_ALL);
//ini_set('display_errors', 1);

require_once 'MainPageWidget.php';
class NodeCommentsWidget extends MainPageWidget {
	public $title = 'Последние комментарии';
  public $from = 'node';
  public $community = array();
  public $community_list = array();
  public $tdi = array();
  public $tdi_list = array();
  public $commentscount = 10;
  public $widget_view = 'WG_NodeCommentsWidget';
  
  private $comments_count = 10;
  private $max_text_length = 240;
  
	public function Render() {
		$this->ctx->rh->UseClass('RL_CyrDate');
		$this->ctx->rh->UseClass("RL_URLGenerator");
    
    $this->commentscount+=0;
    if ( empty($this->commentscount) ) {
      $this->commentscount = $this->comments_count;
    }
    
		$content['title'] = $this->getParam("title");
    $content['from'] = $this->getParam("from");
    
    $user_oids = $this->getUserOIDs();
    
    if ( 'node' == $this->from ) {
      $sql = 'select (select count(*) FROM t_acl_tree as node ' .
      ' left join t_acl_tree as parent on parent.lft <= node.lft and parent.rgt >= node.rgt ' .
      ' left outer join t_acl_list on parent.id_object = t_acl_list.id_acl_tree ' .
      ' where node.id_object = c.oid ' .
      ' and t_acl_list.id_subject in ( ' . join(',', $user_oids) . ' ) ' .
      ' and t_acl_list.`action` in ("item_read", "comment_read") ' .
      ' AND t_acl_list.opt = 2) as disabled, ' .
      ' max(c.oid) as max_oid, c.item_oid, max(o.ctime) as max_ctime ' .
      " from {$this->ctx->store->db->db_prefix}class_comment c " .
      " left join {$this->ctx->store->db->db_prefix}objects o on o.oid = c.oid " .
      " left join {$this->ctx->store->db->db_prefix}objects o2 on o2.oid = c.item_oid " .
      ' where o.is_deleted = 0 and o2.is_deleted = 0 ' .
      ' group by c.item_oid having `disabled` = 0 ' .
      ' order by max_ctime desc limit ' . ($this->commentscount+0);
      
      //print $sql;exit;
    } else {
      $communityWhere = array();
      foreach ( $this->community_list as $community_oid ) {
        $tdi = $this->getTdiList( $community_oid );
        
        if ( !empty($tdi) ) {
          $tdi_list = array();
          
          foreach ( $this->tdi_list as $tdi_oid ) {
            foreach ($tdi as $val) {
              if ( $tdi_oid == $val['oid'] ) {
                $tdi_list[] = $tdi_oid;
                break;
              }
            }
          }
          
          $communityWhere[] = "(a.community_oid = {$community_oid} and a.tdi_oid in (" . join(',', $tdi_list) . '))';
        } else {
          $communityWhere[] = "a.community_oid = {$community_oid}";
        }
      }
      
      $community_string = '(' . join(' or ', $communityWhere) . ')';
      
      $sql = 'select (select count(*) FROM t_acl_tree as node ' .
      ' left join t_acl_tree as parent on parent.lft <= node.lft and parent.rgt >= node.rgt ' .
      ' left outer join t_acl_list on parent.id_object = t_acl_list.id_acl_tree ' .
      ' where node.id_object = c.oid ' .
      ' and t_acl_list.id_subject in ( ' . join(',', $user_oids) . ' ) ' .
      ' and t_acl_list.`action` in ("item_read", "comment_read") ' .
      ' and t_acl_list.opt = 2) as disabled, ' .
      ' max(c.oid) as max_oid, c.item_oid, max(o.ctime) as max_ctime ' .
      " from {$this->ctx->store->db->db_prefix}class_comment c " .
      " left join {$this->ctx->store->db->db_prefix}class_allfeed a on a.oid = c.item_oid " .
      " left join {$this->ctx->store->db->db_prefix}objects o on o.oid = c.oid " .
      " left join {$this->ctx->store->db->db_prefix}objects o2 on o2.oid = c.item_oid " .
      ' where o.is_deleted = 0 and o2.is_deleted = 0 ' .
      " and {$community_string} " .
      ' group by c.item_oid having `disabled` = 0 ' .
      ' order by max_ctime desc limit ' . ($this->commentscount+0);
    }
    
    $result = $this->ctx->store->query($sql);
    
    if ( $result instanceof MysqlDBResult ) {
      while ( $row = $result->next() ) {
        $object = $this->ctx->store->getObject($row['max_oid']);
        
        if ( $object instanceof fobject ) {
          $date_obj = RL_CyrDate::newFromStr("%Y-%m-%d %H:%i:%s", $row['max_ctime']);
          $object->data['comment_time'] = $date_obj->format("%H:%i");
    			$activity_date = $date_obj->format("%j %b");
          
          $object->data['id'] = $object->id;
          $object->data['text'] = trim(strip_tags($object->data['text']));
          
          if ( mb_strlen($object->data['text']) > $this->max_text_length ) {
            $pos = mb_strrpos( mb_substr($object->data['text'], 0, $this->max_text_length), ' ' );
            $object->data['text'] = mb_substr( $object->data['text'], 0, $pos ) . '...';
          }
          
          $object->data['date'] = $activity_date;
          
          $user = $this->ctx->store->getObject($object->data['posted_by_id']);
          $user->data['oid'] = $object->data['posted_by_id'];
          $object->data['user'] = $user->data;
          
          $item = $this->ctx->store->getObject($object->data['item_oid']);
          $object->data['item'] = $item->data;
          
          $community = $this->ctx->store->getObject($item->data['community_oid']);
          $object->data['community'] = $community->data;
          
          $content['comments'][$activity_date][] = $object->data;
        }
      }
    }
    
    if ( !empty($content['comments']) ) {
      $this->content = $content;
    }
    
  	return $this;
  }
  
  public function settingsForm() {
    if ( empty($this->community) ) {
      $rs = $this->ctx->store->find("objects where objects.type = :0 and objects.is_deleted=0 order by objects.ctime desc", array("fcommunity"));
  		while ($obj = $rs->next()) {
  			$this->community[] = array_merge($obj->data, array(
  				'oid' => $obj->id
  			));
  		}
    }
    
    foreach ( $this->community as $key=>$val ) {
      foreach ( $this->community_list as $oid ) {
        if ( $oid == $val['oid'] ) {
          $this->community[$key]['checked'] = true;
          break;
        }
      }
      $tdi_list = $this->getTdiList( $val['oid'] );
      
      foreach ($tdi_list as $index=>$tdi) {
        foreach ($this->tdi_list as $present) {
          if ( $present == $tdi['oid'] ) {
            $tdi_list[$index]['checked'] = true;
          }
        }
      }
      
      $this->community[$key]['tdi'] = $tdi_list;
    }
    
		if ( !isset($this->params) || !isset($this->params['title']) ) {
			$this->params['title'] = $this->title;
      $this->params['from'] = $this->from;
      $this->params['community'] = $this->community;
		}
    
		//return $this->params;
	}
  
  public function setParams( $params ) {
    foreach ( $params as $key=>$val ) {
      if ( isset($this->$key) ) {
        $this->$key = $val;
      }
    }
  }
  
  private function getUserOIDs() {
    $user_oids = array();
    
    if ( isset($this->ctx->mm->aa) && !empty($this->ctx->mm->aa) ) {
      $aa = $this->ctx->mm->aa;
      if ( isset($aa->acl_data['user_id']) && !empty($aa->acl_data['user_id']) ) {
        $user_oids[] = $aa->acl_data['user_id'];
      }
      if ( isset($aa->acl_data['role']['oid']) && !empty($aa->acl_data['role']['oid']) ) {
        $user_oids[] = $aa->acl_data['role']['oid'];
      }
    }
    return $user_oids;
  }
}